package com.example.touch;

import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.util.Log;

import com.example.touch.wifipositioning.GeoPosition;
import com.example.touch.wifipositioning.MACAddress;
import com.example.touch.wifipositioning.PositionCalculationResult;
import com.example.touch.wifipositioning.SignalStrengthSamples;
import com.example.touch.wifipositioning.TraceEntry;
import com.example.touch.wifipositioning.WifiPositioner;

class WifiReceiver extends BroadcastReceiver {

	private WifiManager mainWifi;
	private Activity activity;
	private WifiPositioner wifiPositioner;
	private int size;
    private int index = 0;
    private PositionCalculationResult samples[];
    private int outlierThreshold;

	public WifiReceiver(Activity activity) {
		mainWifi = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
		this.activity = activity;
		wifiPositioner = new WifiPositioner();
		setAverageWindowsSize(5);
		outlierThreshold = 600;
	}

	public void setScanTimer(int miliseconds) {
		Timer t = new Timer();
		t.scheduleAtFixedRate(new TimerTask() {
			WifiManager mainWifi = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);

			@Override
			public void run() {
				mainWifi.startScan();
			}

		}, 0, miliseconds);
	}
	
	public void setAverageWindowsSize(int size)
	{
		this.size = size;
        samples = new PositionCalculationResult[size];
        for (int i = 0; i < size; i++) samples[i] = null;
	}
	
	public void setOutlierThreshold(int pixels)
	{
		outlierThreshold = pixels;
	}

	public void onReceive(Context c, Intent intent) {

		List<ScanResult> wifiList = mainWifi.getScanResults();
		HashMap<String, ScanResult> filteredWifiMap = new HashMap<String, ScanResult>();
		
		TraceEntry onlineTrace = new TraceEntry(new GeoPosition(0, 0));
		SignalStrengthSamples signalStrengthSamples = new SignalStrengthSamples();
		//Log.i("WIFI", "Results: " + wifiList.size());
		for (ScanResult scanResult : wifiList) {
			if(filteredWifiMap.containsKey(scanResult.SSID) == false)
			{
				filteredWifiMap.put(scanResult.SSID, scanResult);
			} else if(scanResult.level > filteredWifiMap.get(scanResult.SSID).level)
			{
				filteredWifiMap.remove(scanResult.SSID);
				filteredWifiMap.put(scanResult.SSID, scanResult);
			}
		}
		
		for (ScanResult scanResult : wifiList) {
			MACAddress macAddress = MACAddress.parse(scanResult.BSSID);
			signalStrengthSamples.put(macAddress, scanResult.level);
			//Log.i("WIFI", "SSID: " + scanResult.SSID + " Strength: " + scanResult.level + " MAC: " + scanResult.BSSID);
		}

		onlineTrace.setSignalStrengthSamples(signalStrengthSamples);

		PositionCalculationResult result = wifiPositioner.fingerPrintKNNWeighted(5, onlineTrace);

		PositionCalculationResult avgResult;
		//if(isOutlier(result, outlierThreshold)){
		//	return;
		//} else {
			avgResult = runningAverage(result);
			add(avgResult);
		//}
			
		
		Intent replyIntent = new Intent("position");
		
		if (result != null) {
			replyIntent.putExtra("x", (int)result.getEstimated().getX());
			replyIntent.putExtra("y", (int)result.getEstimated().getY());
			//Log.i("WIFI", "Estimated: " + result.getEstimated().getX() + " , " + result.getEstimated().getY());
		} else {
			Log.i("WIFI", "Estimated: Not found");
		}

		activity.sendBroadcast(replyIntent);

	}

	
	public void add(PositionCalculationResult x) {
        samples[index] = x;
        if (++index == size) 
        {
        	index = 0; 
        }
    }
	
	private PositionCalculationResult runningAverage(PositionCalculationResult result)
	{
		int i = 0;
		double totalX = result.getEstimated().getX();
		double totalY = result.getEstimated().getY();
		for(PositionCalculationResult previousResult : samples)
		{
			if(previousResult == null){
				continue;
			}
			totalX += previousResult.getEstimated().getX();
			totalY += previousResult.getEstimated().getY();
			i++;
		}
		double avgX = totalX / (i+1);
		double avgY = totalY / (i+1);
		GeoPosition estimated = new GeoPosition(avgX, avgY);
		return new PositionCalculationResult(estimated, result.getReal());
	}
	
	private boolean isOutlier(PositionCalculationResult result, int thresholdPixels)
	{
		int counter = 0;
		for(PositionCalculationResult previousResult : samples)
		{
			if(previousResult == null){
				continue;
			}
			double distance = result.getEstimated().distance(previousResult.getEstimated());
			if(distance > thresholdPixels)
			{
				Log.w("WIFI", "OUTLIER: " + result.getEstimated().toString() + " to " + previousResult.getEstimated().toString() + " Distance: " + distance);
				counter++;			
			}
		}
		if(counter == samples.length){
			return true;
		}
		
		return false;
	}
}
